/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.landery.modules.sinco.service.impl;

import lombok.RequiredArgsConstructor;
import me.landery.modules.sinco.domain.Cert;
import me.landery.modules.sinco.domain.Customize;
import me.landery.modules.sinco.domain.em.CertStatus;
import me.landery.modules.sinco.domain.em.CustomizeStatus;
import me.landery.modules.sinco.repository.CertRepository;
import me.landery.modules.sinco.service.CertService;
import me.landery.modules.sinco.service.dto.CertDto;
import me.landery.modules.sinco.service.dto.CertQueryCriteria;
import me.landery.modules.sinco.service.dto.CustomizeDto;
import me.landery.modules.sinco.service.mapstruct.CertMapper;
import me.landery.modules.system.service.UserService;
import me.landery.modules.system.service.dto.UserDto;
import me.landery.modules.system.service.mapstruct.UserMapper;
import me.landery.utils.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author cc.w
* @date 2022-06-28
**/
@Service
@RequiredArgsConstructor
public class CertServiceImpl implements CertService {

    private final CertRepository certRepository;
    private final CertMapper certMapper;
    private final UserService userService;

    private final UserMapper userMapper;


    @Override
    public Map<String,Object> queryAll(CertQueryCriteria criteria, Pageable pageable){
        Page<Cert> page = certRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(certMapper::toDto));
    }

    @Override
    public List<CertDto> queryAll(CertQueryCriteria criteria){
        return certMapper.toDto(certRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public CertDto findById(Long id) {
        Cert cert = certRepository.findById(id).orElseGet(Cert::new);
        ValidationUtil.isNull(cert.getId(),"Customize","id",id);
        return certMapper.toDto(cert);
    }

    @Override
    @Transactional
    public CertDto findByUserId(Long userId) {
        Cert cert = certRepository.findByUserId(userId);
        return certMapper.toDto(cert);
    }



    public boolean isIDNumber(String IDNumber) {
        if (IDNumber == null || "".equals(IDNumber)) {
            return false;
        }
        // 定义判别用户身份证号的正则表达式（15位或者18位，最后一位可以为字母）
        String regularExpression = "(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|" +
                "(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)";
        //假设18位身份证号码:41000119910101123X  410001 19910101 123X
        //^开头
        //[1-9] 第一位1-9中的一个      4
        //\\d{5} 五位数字           10001（前六位省市县地区）
        //(18|19|20)                19（现阶段可能取值范围18xx-20xx年）
        //\\d{2}                    91（年份）
        //((0[1-9])|(10|11|12))     01（月份）
        //(([0-2][1-9])|10|20|30|31)01（日期）
        //\\d{3} 三位数字            123（第十七位奇数代表男，偶数代表女）
        //[0-9Xx] 0123456789Xx其中的一个 X（第十八位为校验值）
        //$结尾

        //假设15位身份证号码:410001910101123  410001 910101 123
        //^开头
        //[1-9] 第一位1-9中的一个      4
        //\\d{5} 五位数字           10001（前六位省市县地区）
        //\\d{2}                    91（年份）
        //((0[1-9])|(10|11|12))     01（月份）
        //(([0-2][1-9])|10|20|30|31)01（日期）
        //\\d{3} 三位数字            123（第十五位奇数代表男，偶数代表女），15位身份证不含X
        //$结尾
        boolean matches = IDNumber.matches(regularExpression);
        //判断第18位校验值
        if (matches) {
            if (IDNumber.length() == 18) {
                try {
                    char[] charArray = IDNumber.toCharArray();
                    //前十七位加权因子
                    int[] idCardWi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
                    //这是除以11后，可能产生的11位余数对应的验证码
                    String[] idCardY = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
                    int sum = 0;
                    for (int i = 0; i < idCardWi.length; i++) {
                        int current = Integer.parseInt(String.valueOf(charArray[i]));
                        int count = current * idCardWi[i];
                        sum += count;
                    }
                    char idCardLast = charArray[17];
                    int idCardMod = sum % 11;
                    if (idCardY[idCardMod].toUpperCase().equals(String.valueOf(idCardLast).toUpperCase())) {
                        return true;
                    } else {
                        return false;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }
        }
        return matches;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public CertDto create(Cert resources) {
        //判断身份证格式是否正确
        if(resources.getCertnum() != null){
            if(!isIDNumber(resources.getCertnum())){
                throw new IllegalArgumentException("身份证号不正确");
            }
        }
        Cert cert = certRepository.findByCertnum(resources.getCertnum());
        if(cert != null){
            throw new IllegalArgumentException("已存在提交请求，无需重复提交");
        }
        Long userId = SecurityUtils.getCurrentUserId();
        UserDto userDto = userService.findById(userId);
        resources.setUser(userMapper.toEntity(userDto));
        resources.setStatus(CertStatus.WAITING.getCode());
        return certMapper.toDto(certRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Cert resources) {
        Cert cert = certRepository.findById(resources.getId()).orElseGet(Cert::new);
        ValidationUtil.isNull( cert.getId(),"Cert","id",resources.getId());
        cert.copy(resources);
        certRepository.save(cert);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            certRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<CertDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (CertDto cert : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户名", cert.getUser().getUsername());
            map.put("身份证号码", cert.getCertnum());
            map.put("真实姓名", cert.getRealname());
            map.put("身份证正面", cert.getImgFront());
            map.put("身份证反面", cert.getImgBack());
            map.put("创建日期", cert.getCreateTime());
            map.put("更新时间", cert.getUpdateTime());
            map.put("创建者", cert.getCreateBy());
            map.put("更新者", cert.getUpdateBy());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}